package com.dcjt.firehotcarpad.model

import android.content.Context
import android.util.Log
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.ToastUtil
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.Escape
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject
import sun.misc.BASE64Decoder
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.zip.GZIPInputStream

/**
 * 发消息
 */
class SendMessageUtils private constructor() {
    companion object {
        private var instance: SendMessageUtils? = null
            get() {
                if (field == null) {
                    field = SendMessageUtils()
                }
                return field
            }
        @Synchronized
        fun get(): SendMessageUtils{
            return instance!!
        }
    }

    /**
     * 车辆状态改变发送消息
     */
    fun sendMessage(
        cmd: String,
        zqId: String,
        context: Context,
        obj: Any?
    ){
        if ( DataManager.getInstance().user == null || DataManager.getInstance().appConfigEntity == null){
            ToastUtil.show("人员信息配置出现错误！")
            return
        }

        val msg = HashMap<String, Any>()
        msg["zqid"] = zqId
        msg["clid"] = DataManager.getInstance().user.account
        if (DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.buZ_CLZT_SET == cmd){
            msg["upclxx"] = obj as Any
        }
        msg["sendUserId"] = DataManager.getInstance().user.id
        msg["sendUserName"] = DataManager.getInstance().user.real_name//泡沫（PM）川X5847应急
//        msg["sendUserName"] = "车牌号测试"//泡沫（PM）川X5847应急
        msg["depts"] = DataManager.getInstance().user.dept_id
        if (cmd ==  DataManager.getInstance().appConfigEntity.jcj_pmqEnum.jcJ_Cmd.zhzX_RWZL){
            msg["type"] = 0
            msg["id"] = obj.toString() //指令id
        }

        val data = HashMap<String, Any>()
        data["cmd"] =cmd
        data["msg"] = msg
        LoggerManager.e("sendMessage_msg:" + Gson().toJson(msg))

        val message = HashMap<String, Any>()
        message["from"] = DataManager.getInstance().pmqBean.uid
        message["gid"] =  DataManager.getInstance().pmqBean.gid
        message["online"] = 1
        // 消息内容加密后发送
        message["data"] = compile(Gson().toJson(data))

        val map = HashMap<String, Any>()
        map["aid"] = DataManager.getInstance().pmqBean.aid
        map["access_token"] = DataManager.getInstance().pmqBean.access_token
        map["message"] = message
//        val messageUrl = DataManager.getInstance().appConfigEntity.appServerUrl.pmqUrl
        var messageUrl = SPUtil.get( context, SPConstant.MESSAGE_URL_PORT, "")

        LoggerManager.e("sendMessage:" + Gson().toJson(map))

        ApiRepository1.getInstance().sendMessage_zl(map, messageUrl as String?)
            .subscribe(object : FastObserver<ResponseBody>() {
                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    ToastUtil.show("消息服务异常")
                    Log.e("_onError", "_onNext: " +e)
                }

                override fun _onNext(entity: ResponseBody) {
                    val response: String = entity.string()
                    val msg = uncompress(response.substring("PMQ/gz".length)) //
                    val obj = JSONObject(msg)
                    ToastUtil.show(obj.optString("message"))
                }
            })
    }

//    /**
//     * 自定义加密
//     * @param {json} code 数据
//     */
//    fun compile(code: String): String {
//        val info = StringBuilder()
//        info.append((code[0].toInt() + code.length).toChar())
//        for (i in 1 until code.length) {
//            info.append((code[i].toInt() + code[i - 1].toInt()).toChar())
//        }
//        return escape(info.toString())
//    }
    /**
     * 自定义加密
     * @param {json} code 数据
     */
    fun compile(code: String): String {
        val info = StringBuilder()
        info.append((code[0].toInt() + code.length).toChar())
        for (i in 1 until code.length) {
            info.append((code[i].toInt() + code[i - 1].toInt()).toChar())
        }
//        return info.toString()
        return  Escape.escape(info.toString())
    }


    /**
     * 自定义解密
     * @param {*} code 数据
     */
    fun unCompile(value: String): String {
        val code = unescape(value)
        val info = StringBuilder()
        info.append((code[0].toInt() - code.length).toChar())
        for (i in 1 until code.length) {
            info.append((code[i].toInt() - info[i - 1].toInt()).toChar())
        }
        LoggerManager.d("解压内容：${info.toString()}")
        return info.toString()
    }

    fun unescape(src: String): String {
        val tmp = StringBuffer()
        tmp.ensureCapacity(src.length)
        var lastPos = 0
        var pos = 0
        var ch: Char
        while (lastPos < src.length) {
            pos = src.indexOf("%", lastPos)
            if (pos == lastPos) {
                if (src[pos + 1] == 'u') {
                    ch = src
                        .substring(pos + 2, pos + 6).toInt(16).toChar()
                    tmp.append(ch)
                    lastPos = pos + 6
                } else {
                    ch = src
                        .substring(pos + 1, pos + 3).toInt(16).toChar()
                    tmp.append(ch)
                    lastPos = pos + 3
                }
            } else {
                lastPos = if (pos == -1) {
                    tmp.append(src.substring(lastPos))
                    src.length
                } else {
                    tmp.append(src.substring(lastPos, pos))
                    pos
                }
            }
        }
        return tmp.toString()
    }

    /*
  * 对应javascript的escape()函数, 加码后的串可直接使用javascript的unescape()进行解码
  */
    fun escape(src: String): String {
        var i: Int=0
        var j: Char
        val tmp = StringBuffer()
        tmp.ensureCapacity(src.length * 6)
//        i = 0
        while (i < src.length) {
            j = src[i]
            if (Character.isDigit(j) || Character.isLowerCase(j)
                || Character.isUpperCase(j)
            ) tmp.append(j) else if (j.toInt() < 256) {
                tmp.append("%")
                if (j.toInt() < 16) tmp.append("0")
                tmp.append(j.toInt().toString(16))
            } else {
                tmp.append("%u")
                tmp.append(j.toInt().toString(16))
            }
            i++
        }
        return tmp.toString()
    }


    /**
     * 解压消息内容
     */
    fun uncompress(value: String): String {
        var result: String = ""
        var out: ByteArrayOutputStream? = null
        var byteArrayIS: ByteArrayInputStream? = null
        var gzipInputStream: GZIPInputStream? = null
        try {
            out = ByteArrayOutputStream()
//            val compressed = BASE64Decoder().decodeBuffer(value)
            val compressed = BASE64Decoder().decodeBuffer(value)
            byteArrayIS = ByteArrayInputStream(compressed)
            gzipInputStream = GZIPInputStream(byteArrayIS)
            val buffer = ByteArray(1024)
            var offset = -1
            while (gzipInputStream.read(buffer).also { offset = it } != -1) {
                out.write(buffer, 0, offset)
            }
            result = out.toString()
        } finally {
            out?.close()
            byteArrayIS?.close()
            gzipInputStream?.close()
        }
        return result
    }


}
